<script setup lang="ts">
import { getWorkbenchDataAPI } from '@/apis/common'
import { ref, onMounted, watch, onUnmounted, nextTick } from 'vue'
import type { WorkbenchData } from '@/types/common'
import * as echarts from 'echarts'
import { useRouter } from 'vue-router'

const workbenchData = ref<WorkbenchData>({
  annualIncome: 0,
  annualIncomeArray: {
    xmonth: [],
    ybuilding: [],
    yparking: []
  },
  chargePoleTotal: 0,
  enterpriseTotal: 0,
  monthCardTotal: 0
})

// 获取工作台数据
const getWorkbenchData = async () => {
  const res = await getWorkbenchDataAPI()
  console.log(res)
  workbenchData.value = res.data
  // 获取数据后初始化/更新图表
  nextTick(() => {
    if (!chartInstance) {
      initChart()
    }
    updateChart()
  })
}

// 页面加载时获取数据
getWorkbenchData()

// 图表实例
let chartInstance: echarts.ECharts | null = null

// 初始化图表
const initChart = () => {
  const chartDom = document.getElementById('incomeChart')
  if (!chartDom) return
  chartInstance = echarts.init(chartDom)
}

// 更新图表数据
const updateChart = () => {
  if (!chartInstance) return
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['物业费', '行车收入'],
      right: 20,
      top: 20
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '80px',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: workbenchData.value.annualIncomeArray.xmonth.map(month => `${month}月`),
      axisLine: {
        lineStyle: {
          color: '#E5E6EB'
        }
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 7000,
      interval: 1000,
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#E5E6EB'
        }
      }
    },
    series: [
      {
        name: '物业费',
        type: 'bar',
        barWidth: 20,
        data: workbenchData.value.annualIncomeArray.ybuilding,
        itemStyle: {
          color: '#4D70FF'
        }
      },
      {
        name: '行车收入',
        type: 'bar',
        barWidth: 20,
        data: workbenchData.value.annualIncomeArray.yparking,
        itemStyle: {
          color: '#BEC3CC'
        }
      }
    ]
  }

  chartInstance.setOption(option)
}

onMounted(() => {
  // 获取数据
  getWorkbenchData()
  
  // 监听窗口变化，重绘图表
  window.addEventListener('resize', () => {
    chartInstance?.resize()
  })
})

// 监听数据变化，更新图表
watch(() => workbenchData.value.annualIncomeArray, () => {
  updateChart()
}, { deep: true })

// 组件卸载时销毁图表
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', () => {
    chartInstance?.resize()
  })
})
</script>

<template>
  <div class="workbench-page">
    <el-row :gutter="20">
      <el-col :span="17">
        <div class="card-container">
          <div class="card-title">园区数据</div>
          <div class="card-statistic">
            <el-statistic :value="workbenchData.annualIncome">
              <template #title>年度累计收费（元）</template>
            </el-statistic>
            <el-statistic :value="workbenchData.enterpriseTotal">
              <template #title>入驻企业总数（个）</template>
            </el-statistic>
            <el-statistic :value="workbenchData.monthCardTotal">
              <template #title>月卡车辆总数（辆）</template>
            </el-statistic>
            <el-statistic :value="workbenchData.chargePoleTotal">
              <template #title>一体杆总数（台）</template>
            </el-statistic>
          </div>
        </div>
        <div class="card-container">
          <div class="card-title">年度收入统计</div>
          <div id="incomeChart" class="chart-container"></div>
        </div>
        <div class="card-container">
          <div class="card-title">快捷入口</div>
        </div>
      </el-col>
      <el-col :span="7">
        <div class="card-container">
          <div class="card-title">快捷入口</div>
          <div class="card-entry">
            <div class="card-entry-item" @click="$router.push('/exterpriseAdd')">
              <img src="@/assets/entry-enterprise.png" alt="" />
              <span>添加企业</span>
            </div>
            <div class="card-entry-item" @click="$router.push('/sys/user')">
              <img src="@/assets/entry-employee.png" alt="" />
              <span>员工管理</span>
            </div>
            <div class="card-entry-item" @click="$router.push(`/propety/cost/?type=${'workbench'}`)">
              <img src="@/assets/entry-bill.png" alt="" />
              <span>添加账单</span>
            </div>
            <div class="card-entry-item">
              <img src="@/assets/entry-screen.png" alt="" />
              <span>数据大屏</span>
            </div>
          </div>
        </div>
        <div class="card-container">
          <div class="card-title">快捷入口</div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.workbench-page {
  background-color: #f4f6f8;
  height: 100%;
  .card-container {
    background-color: #fff;
    padding: 20px;
    margin-bottom: 20px;
  }
  .card-title {
    margin-bottom: 20px;
    font-size: 14px;
    font-weight: 500;
  }
  .card-statistic {
    display: flex;
    justify-content: space-between;
  }
}

.el-statistic {
  --el-statistic-content-font-size: 28px;
  --el-statistic-title-font-size: 13px;
}
:deep(.el-statistic__head) {
  margin-bottom: 12px;
}

.card-entry {
  display: flex;
  justify-content: space-between;
  &-item {
    text-align: center;
    img {
      width: 40px;
    }
    span {
      font-size: 12px;
      display: block;
      margin-top: 8px;
    }
  }
}

.chart-container {
  width: 100%;
  height: 400px;
  margin-top: 20px;
}
</style>
